package com.ruoyi.basics.controller;

import java.util.*;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.framework.shiro.session.OnlineSession;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.system.domain.SysDept;
import com.ruoyi.system.domain.SysDictData;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysDictDataService;
import com.sun.corba.se.impl.corba.ServerRequestImpl;
import org.apache.poi.ss.formula.functions.T;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.session.Session;
import org.omg.CORBA.Context;
import org.omg.CORBA.ServerRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.basics.domain.User;
import com.ruoyi.basics.service.IUserService;
import com.ruoyi.framework.web.base.BaseController;
import com.ruoyi.common.page.TableDataInfo;
import com.ruoyi.common.base.AjaxResult;
import com.ruoyi.common.utils.ExcelUtil;

/**
 * 大用户基础数据 信息操作处理
 * 
 * @author wangbing
 * @date 2018-12-28
 */
@Controller
@RequestMapping("/basics/user")
public class UserController extends BaseController
{
    private String prefix = "basics/user";
	
	@Autowired
	private IUserService userService;
	@Autowired
	private ISysDictDataService dictDataService;
	@Autowired
	private ISysDeptService deptService;
	
	@RequiresPermissions("basics:user:view")
	@GetMapping()
	public String user()
	{
	    return prefix + "/user";
	}
	
	/**
	 * 查询大用户基础数据列表
	 */
	@RequiresPermissions("basics:user:list")
	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(User user)
	{

		startPage();
//        List<User> list = userService.selectUserList(user);
        List<User> list = userService.selectUserListByData(user);
		return getDataTable(list);
	}

	/**
	 * 详细列表
	 */
	@RequiresPermissions("basics:user:list")
	@GetMapping("/detail/{userId}")
	public String detail(@PathVariable("userId") Long userId, ModelMap mmap)
	{
		mmap.put("user", userService.selectUserById(userId));
		return "basics/point/point";
	}
	
	
	/**
	 * 导出大用户基础数据列表
	 */
	@RequiresPermissions("basics:user:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(User user)
    {
    	List<User> list = userService.selectUserList(user);
        ExcelUtil<User> util = new ExcelUtil<User>(User.class);
        return util.exportExcel(list, "user");
    }
	
	/**
	 * 新增大用户基础数据
	 */
	@GetMapping("/add")
	public String add()
	{
	    return prefix + "/add";
	}
	
	/**
	 * 新增保存大用户基础数据
	 */
	@RequiresPermissions("basics:user:add")
	@Log(title = "大用户基础数据", businessType = BusinessType.INSERT)
	@PostMapping("/add")
	@ResponseBody
	public AjaxResult addSave(User user)
	{
		user.setUserId(getSysUser().getUserId());
		user.setAddDate(new Date());
		return toAjax(userService.insertUser(user));
	}

	/**
	 * 修改大用户基础数据
	 */
	@GetMapping("/edit/{id}")
	public String edit(@PathVariable("id") Long id, ModelMap mmap)
	{
		User user = userService.selectUserById(id);
		mmap.put("user", user);
	    return prefix + "/edit";
	}
	
	/**
	 * 修改保存大用户基础数据
	 */
	@RequiresPermissions("basics:user:edit")
	@Log(title = "大用户基础数据", businessType = BusinessType.UPDATE)
	@PostMapping("/edit")
	@ResponseBody
	public AjaxResult editSave(User user)
	{
		List<String> list = new ArrayList();
		String s119 = user.getUserType();

		for (String s : s119.split(",")) {
			list.add(s);
		}
		List<String> list1 = removeDuplicate(list);
		StringBuffer uT = new StringBuffer();
		for (String s : list1) {
			uT.append(s);
			uT.append(",");
		}
		int end = uT.length()-1;
		String newUT = uT.substring(0,end);
		user.setUserType(newUT);
		return toAjax(userService.updateUser(user));
	}

	/**
	 * 删除大用户基础数据
	 */
	@RequiresPermissions("basics:user:remove")
	@Log(title = "大用户基础数据", businessType = BusinessType.DELETE)
	@PostMapping( "/remove")
	@ResponseBody
	public AjaxResult remove(String ids)
	{		
		return toAjax(userService.deleteUserByIds(ids));
	}



	@PostMapping("/LargeUser")
	@ResponseBody
	public List<Map<String, Object>> LargeUser(ModelMap mmap)
	{
		ShiroUtils session = new ShiroUtils();
		SysUser users = session.getSysUser();			// 用户信息
		String userId = session.getUserId().toString(); // 用户ID
		String loginName = session.getLoginName();		// 登录名
		String deptId = users.getDeptId().toString();	// 部门ID
		//判断当前登录用户的deptId是不是103管理员的，如果是则查询所有供电单位；
		// 如果不是，则只查询本供电单位的信息
		List<Map<String, Object>> deptList = new ArrayList<>();
		if (!deptId.equals("103")) {
			SysDept sd =  deptService.selectDeptById(Long.parseLong(deptId));
			deptList = deptService.selectDeptTree(sd);
		}else{
			deptList = deptService.selectDeptTree(new SysDept());
		}

		// 有多少个供电单位
		List<Map<String, Object>> usertList = new ArrayList<>();
		for (Map<String, Object> map : deptList) {
			Map<String, Object> deptMap = new HashMap<String, Object>();
			if(!map.get("name").equals("乐山电力")){
				Integer num = userService.CountLargeUser(Long.parseLong(map.get("id").toString()));
				if(num == 0){
					deptMap.put("num",0);
				}else
					deptMap.put("num",num);
				deptMap.put("name",map.get("name"));
				usertList.add(deptMap);
			}
		}
		return usertList;
	}


	/**
	 *  list 去重
	 *
	 * @param list
	 * @return
	 */
	public static List<String> removeDuplicate(List<String> list){
			Set<String> set = new  HashSet<String>();
			List<String> newList = new  ArrayList<String>();
			for (String t :list) {
				if(set.add(t)){
					newList.add(t);
				}
			}
			return newList;
	}

}
